﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using GameViewer.Core.Archives;

namespace GameViewer.Core.Archives
{
    public class ArchiveManager : Singleton<ArchiveManager>
    {
        Dictionary<string, Archive> mArchives = new Dictionary<string, Archive>();
        Dictionary<string, ArchiveFactory> mArchFactories = new Dictionary<string, ArchiveFactory>();

        public ArchiveManager()
        {
        }

        public void AddFactory(ArchiveFactory factory)
        {
            mArchFactories.Add(factory.Type, factory);
        }

        public Archive Load(string fileName)
        {
            string ext = "";
            if (System.IO.Directory.Exists(fileName))
            {
                ext = "FileSystem";
            }
            else if(System.IO.Path.HasExtension(fileName))
            {
                ext = System.IO.Path.GetExtension(fileName).ToUpper().Remove(0, 1);
            }
            return Load(fileName, ext);
        }

        public Archive Load(string fileName, string archType)
        {
            if (mArchives.ContainsKey(fileName))
            {
                return mArchives[fileName];
            }
            else
            {
                if (mArchFactories.ContainsKey(archType))
                {
                    Archive archive = mArchFactories[archType].CreateInstance(fileName);
                    archive.Load();
                    mArchives.Add(fileName, archive);
                    return archive;
                }
                else
                {
                    return null;
                }
            }
        }

        public Dictionary<string, Archive> Archives
        {
            get
            {
                return mArchives;
            }
        }
    }
}
